package com.invest.infra.mvc.utils;

import com.invest.utils.check.ValidatorUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * <p>注释</p>
 *
 * @author yuyizhao
 * @version v0.1 2016/3/2 Exp
 */
public abstract  class JsonResultTemplate<REQ,RES> {

    private static final Logger LOGGER = LoggerFactory.getLogger(JsonResultTemplate.class);
        public String execute(REQ request){
            try{

            //1.记录日志
            LOGGER.info("request={}",request);
             //执行校验
             List<String> errors = ValidatorUtil.validateAll(request);
            if(CollectionUtils.isNotEmpty(errors)){
                MvcResult result = new MvcResult();
                result.addAllGlobalError(errors);
                return MvcResultUtils.toJsonStr(result);
            }

             //3.执行业务逻辑
            RES ext = doService(request);
            //4.返回结果
            MvcResult result = new MvcResult();
            result.setExtObj(ext);
            return MvcResultUtils.toJsonStr(result);

        }catch (IllegalArgumentException ex){
                //记录异常
                LOGGER.error("系统请求参数错误",ex);
                MvcResult result = new MvcResult();
                result.addGlobalError(ex.getMessage());
                return MvcResultUtils.toJsonStr(result);
         }catch (IllegalStateException ex){
                //记录异常
                LOGGER.error("数据状态错误",ex);
                MvcResult result = new MvcResult();
                result.addGlobalError(ex.getMessage());
                return MvcResultUtils.toJsonStr(result);
         }catch(Exception ex){
            //记录异常
            LOGGER.error("系统请求异常",ex);
            MvcResult result = new MvcResult();
            result.addGlobalError("系统请求异常");
            return MvcResultUtils.toJsonStr(result);
        }
    }



    protected abstract RES doService(REQ request);

}
